<?php
declare (strict_types=1);

namespace app\api\controller;

use think\facade\View;
use think\response\Json;
use app\common\model\Transfer as TransferModel;
use think\exception\ValidateException;

class Transfer extends Base
{

    public function index(): Json
    {
        $result['transfer_account'] = [
            [
                'title' => '电子币',
                'type' => 'currency',
                'balance' => $this->user->assets->currency
            ],
            [
                'title' => '奖金',
                'type' => 'bonus',
                'balance' => $this->user->assets->bonus
            ],

        ];
        $result['transfer_factor'] = [
            'transfer_open' => $this->system['transfer_open'],
            'transfer_min' => $this->system['transfer_min'],
            'transfer_cost' => $this->system['transfer_cost'],
            'transfer_msg' => $this->system['transfer_msg'],
        ];
        return json(['code' => 1, 'msg' => 'success', 'result' => $result]);
    }


    public function getList(): Json
    {
        $param = $this->request->param();

        $map = ['uid|take_uid' => $this->user->id];
        $list = TransferModel::getPageList($map, 'id,account,uid,amount,cost,real_amount,take_uid,create_time
        ', $param['page'], 20, false, ['take', 'user']);

        foreach ($list['result'] as &$v) {
            if ($v->uid == $this->user->id) {
                $v->trStatus = '转出';
                $v->trUser = $v->take->code;
            } else {
                $v->trStatus = '转入';
                $v->trUser = $v->user->code;
            }
            unset($v->uid);
            unset($v->take_uid);
            unset($v->take);
            unset($v->user);
        }
        return json($list);
    }

    public function verify(): Json
    {
        $code = $this->request->param('code');
        $nickname = \app\common\model\User::where('code', $code)->value('nickname');
        if ($nickname) {
            return json(['code' => 1, 'result' => $nickname]);
        } else {
            return json(['code' => -1, 'result' => '会员不存在']);
        }
    }

    public function save(): Json
    {
        if (!$this->user->pay_password) {
            return json(['code' => -1, 'msg' => '您尚未设置支付密码，请先去安全中心设置支付密码']);
        }
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Transfer');
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
        return json(TransferModel::add($param, $this->user, $this->system));
    }

}

